package com.emmy.walnut.presenter;

import android.os.Handler;
import android.os.Message;

import com.emmy.walnut.app.AppDatabase;
import com.emmy.walnut.constant.AppConstant;
import com.emmy.walnut.model.Label;
import com.emmy.walnut.presenter.iface.ClassPIface;
import com.emmy.walnut.view.iface.ClassIface;

import java.util.List;

/**
 * @ClassName ClassPresenter
 * @Description TODO
 * @Author zhouxuan
 * @Date 2020/02/14 20:22
 * @Version 1.0
 */
public class ClassPresenter implements ClassPIface {

    private ClassIface classIface;

    public ClassPresenter(ClassIface classIface){
        this.classIface = classIface;
    }

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what){
                case AppConstant.ADD_LABEL_SUSCESS:
                    classIface.addLabelSuccess((Label)msg.obj);
                    break;
                case AppConstant.DUPLICATE_LABEL:
                    classIface.addLabelDuplicate();
                    break;
            }
            return false;
        }
    });

    @Override
    public void addLabel(final String labelName) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<Label> results = AppDatabase.getInstance().labelDao().getLabelWithUserAndLabel(
                        AppConstant.username, labelName);
                if (results!=null&&results.size()!=0){
                    Message.obtain(handler, AppConstant.DUPLICATE_LABEL).sendToTarget();
                    return;
                }
                Label label = new Label(labelName, true, AppConstant.username);
                long id = AppDatabase.getInstance().labelDao().insert(label);
                label.setId((int)id);
                Message.obtain(handler, AppConstant.ADD_LABEL_SUSCESS, label).sendToTarget();
            }
        }).start();
    }
}
